<?php

class SiteController extends Controller {

    public function filters() {
        return array(
            'accessControl', // perform access control for CRUD operations
        );
    }

    /**
     * Specifies the access control rules.
     * This method is used by the 'accessControl' filter.
     * @return array access control rules
     */
    public function accessRules() {
        return array(
            array('allow', // allow all users to access 'index' and 'view' actions.
                'actions' => array('index', 'register', 'login', 'logout'),
                'users' => array('*'),
            ),
//            array('deny', // allow all users to access 'index' and 'view' actions.
//                'actions' => array('register', 'login'),
//                'users' => array('?'),
//            ),
            array('allow', // deny all users
                'users' => array('*'),
            ),
        );
    }

    public function init() {
        $cs = Yii::app()->clientScript;
        $cs->registerCssFile(Yii::app()->baseUrl . '/css/common.css');
        $cs->registerCssFile(Yii::app()->baseUrl . '/css/v3/n_common.css');
        $cs->registerScriptFile(Yii::app()->request->baseUrl . "/js/common.js", CClientScript::POS_HEAD);
        $cs->registerScriptFile(Yii::app()->request->baseUrl . "/js/v3/n_common.js", CClientScript::POS_HEAD);
        $cs->registerCoreScript('jquery');
        $cs->registerCoreScript('jquery.ui');
        $cs->registerScriptFile(Yii::app()->request->baseUrl . "/js/jquery.placeholder.js", CClientScript::POS_HEAD);
    }

    /**
     * Declares class-based actions.
     */
    public function actions() {
        return array(
            // captcha action renders the CAPTCHA image displayed on the contact page
            'captcha' => array(
                'class' => 'CCaptchaAction',
                'backColor' => 0xFFFFFF,
            ),
            // page action renders "static" pages stored under 'protected/views/site/pages'
            // They can be accessed via: index.php?r=site/page&view=FileName
            'page' => array(
                'class' => 'CViewAction',
            ),
        );
    }

    public function actionAjaxproduct(){ 
        
        $sort = $_GET['sort'];
        $num = isset($_GET['num'])?$_GET['num']:9;
        $page = isset($_GET['page'])?$_GET['page']:1;

        /*
         * 获取cookie商圈ID
         */
        $cookie = Yii::app()->request->getCookies();
        $zonecookie = (string) $cookie['zone'];
        $zonecookie = !$zonecookie ? '2' : $zonecookie;
        $zoneid = !$zonecookie ? '&fq=zoneId:2' : '&fq=zoneId:' . $zonecookie;

        $start = ($page-1)*9;

        $data = @file_get_contents('http://' . Yii::app()->params['apiHostProduct'] . ':' . Yii::app()->params['apiPortProduct'] . '/ProductCenter/select?q=**' . $zoneid . '&fq=status:1&wt=json&indent=true&start='.$start.'&rows='.$num.'&sort='.$sort.'+desc');
        $data = CJSON::decode($data);
        $row = $data['QueryResponse']['results'];
        foreach ($row as $key => $value) {
            $value['url'] = Yii::app()->createUrl('site/product', array('id' => $value['productSkuId']));
            $value['skuPrice'] = number_format($value['skuPrice'], 2);
            $value['productImg'] = $value['productImg']['0'];
            $value['comment']['content'] = strip_tags($value['comment']['content']);
            $value['comment']['buyerImg'] = empty($value['comment']['buyerImg'])?Yii::app()->request->baseUrl.'/images/icon50.jpg':$value['comment']['buyerImg'];
            $row[$key] = $value;

        }
        echo json_encode($row);
        exit;
        
    }

    public function actionIndex() {
        $cs = Yii::app()->clientScript;
        $cs->registerCssFile(Yii::app()->baseUrl . '/css/index.css');
        $commonclass = new CommonClass();

        /*
         * 获取cookie商圈ID
         */
        $cookie = Yii::app()->request->getCookies();
        $zonecookie = (string) $cookie['zone'];
        $zonecookie = !$zonecookie ? '2' : $zonecookie;
        $zoneid = !$zonecookie ? '&fq=zoneId:2' : '&fq=zoneId:' . $zonecookie;
        $zone_row = $commonclass->zoneProduct($zonecookie);

        //banner
        $banner = @file_get_contents('http://61.183.9.246:8060/LdAccountServer/userAccount/getAdvertImg');
        $banner = CJSON::decode($banner);

        /*
         * 精品推荐  $zone_row['tj']
         */
         //http://61.183.9.246:8090/ProductCenter/select?q=**&fq=recommend:1&wt=json&indent=true
        $row_tj = @file_get_contents('http://' . Yii::app()->params['apiHostProduct'] . ':' . Yii::app()->params['apiPortProduct'] . '/ProductCenter/select?q=**'. $zoneid . '&fq=recommend:1&wt=json&indent=true&start=0&rows=3&sort=saleCount+desc');
        $row_tj = CJSON::decode($row_tj);

        /*
         * 特价  $zone_row['ol']
         */
        //http://61.183.9.246:8090/ProductCenter/select?q=**&sort=percent+asc&fq=zoneId:1&fq=status=1&rows=5&wt=json&indent=true
        $row_ol = @file_get_contents('http://' . Yii::app()->params['apiHostProduct'] . ':' . Yii::app()->params['apiPortProduct'] . '/ProductCenter/select?q=**' . $zoneid . '&fq=status:1&wt=json&indent=true&start=0&rows=5&sort=percent+asc');
        $row_ol = CJSON::decode($row_ol);
        
        /*
         * 清爽一夏  $zone_row['summer']
         */
        // $row_summer = @file_get_contents('http://' . Yii::app()->params['apiHostProduct'] . ':' . Yii::app()->params['apiPortProduct'] . '/ProductCenter/select?q=**' . $zoneid . '&fq=status:1&wt=json&indent=true&start=14&rows=9&sort=saleCount+desc');
        // $row_summer = CJSON::decode($row_summer);

        //销量http://61.183.9.246:8090/ProductCenter/select?q=**&sort=saleCount+desc&fq=zoneId:1&fq=status=1&rows=3&wt=json&indent=true
        $row_sales = @file_get_contents('http://' . Yii::app()->params['apiHostProduct'] . ':' . Yii::app()->params['apiPortProduct'] . '/ProductCenter/select?q=**' . $zoneid . '&fq=status:1&wt=json&indent=true&start=0&rows=9&sort=saleCount+desc');
        $row_sales = CJSON::decode($row_sales);
        //评价
        $row_commont = @file_get_contents('http://' . Yii::app()->params['apiHostProduct'] . ':' . Yii::app()->params['apiPortProduct'] . '/ProductCenter/select?q=**' . $zoneid . '&fq=status:1&wt=json&indent=true&start=0&rows=9&sort=commontCount+desc');
        $row_commont = CJSON::decode($row_commont);
        //价格
        $row_collection = @file_get_contents('http://' . Yii::app()->params['apiHostProduct'] . ':' . Yii::app()->params['apiPortProduct'] . '/ProductCenter/select?q=**' . $zoneid . '&fq=status:1&wt=json&indent=true&start=0&rows=9&sort=skuPrice+desc');
        $row_collection = CJSON::decode($row_collection);
        
//        print_r($row_ol);
//        print_r($row);
//        $row_hot_week = @file_get_contents('http://' . Yii::app()->params['apiHostProduct'] . ':' . Yii::app()->params['apiPortProduct'] . '/ProductCenter/select?q=create_time:2014-07-08 19:23:19&wt=json&indent=true&sort=sale_count+des');

        /*
         * 周排行
         */
//        $row_hot_week = @file_get_contents('http://' . Yii::app()->params['apiHostProduct'] . ':' . Yii::app()->params['apiPortProduct'] . '/ProductCenter/select?q=**'.$zoneid.'&fq=status:1&wt=json&indent=true&sort=saleCount+desc&start=0&rows=10');
//        $row_hot_week = CJSON::decode($row_hot_week);
//         echo '<pre>';
//        print_r($banner);
// echo '</pre>';
        /*
         * 月排行
         */
//        $row_hot_month = @file_get_contents('http://' . Yii::app()->params['apiHostProduct'] . ':' . Yii::app()->params['apiPortProduct'] . '/ProductCenter/select?q=**'.$zoneid.'&fq=status:1&wt=json&indent=true&sort=clickCount+desc&start=0&rows=10');
//        $row_hot_month = CJSON::decode($row_hot_month);

        /*
         * 排行序号
         */
//        $ordernum = array(
//            '1' => 'hotnum_red',
//            '2' => 'hotnum_orange',
//            '3' => 'hotnum_orange',
//            '4' => 'hotnum_yellow',
//            '5' => 'hotnum_yellow',
//            '6' => 'hotnum_yellow',
//            '7' => 'hotnum_blue',
//            '8' => 'hotnum_blue',
//            '9' => 'hotnum_blue',
//            '10' => 'hotnum_blue',
//        );

        $this->render('index', array('model' => $row_tj['QueryResponse']['results'], 'row_ol' => $row_ol['QueryResponse']['results'], 'row_summer' => $row_summer['QueryResponse']['results'], 'row_sales' => $row_sales['QueryResponse']['results'], 'row_commont' => $row_commont['QueryResponse']['results'], 'row_collection' => $row_collection['QueryResponse']['results'], 'banner' => $banner['GetHeadImgListRsp']['list']));
    }

    public function actionProduct() {
        $allcount = 0;
        $skuValueId = array();
        $skuValue = array();

        /*
         * 获取cookie商圈ID
         */
        $cookie = Yii::app()->request->getCookies();
        $zonecookie = (string) $cookie['zone'];
        $zonecookie = !$zonecookie ? '2' : $zonecookie;
        $zoneid = !$zonecookie ? '&fq=zoneId:2' : '&fq=zoneId:' . $zonecookie;


//        $api = new Api('product');
        $api2 = new Api('account');

        $cs = Yii::app()->clientScript;
        $cs->registerCssFile(Yii::app()->baseUrl . '/css/food.css');
        $cs->registerScriptFile(Yii::app()->request->baseUrl . "/js/product.js", CClientScript::POS_HEAD);
        $model = new ProductForm();
        $productSkuId = $_GET['id'];
        $row = @file_get_contents('http://' . Yii::app()->params['apiHostProduct'] . ':' . Yii::app()->params['apiPortProduct'] . '/ProductCenter/skuInfo?productSkuId=' . $productSkuId);
        $row = CJSON::decode($row);
        //print_r($row);

        $productSku = $row['productSku'];
//        print_r($productSku);

        for ($i = 0; $i < count($productSku); $i++) {
            $newskuValue = explode(',', $productSku[$i]['skuSelectValue']);
            sort($newskuValue);
            $newskuValue = implode(',', $newskuValue);
            $skuprice[$newskuValue]['skuPrice'] = number_format($productSku[$i]['skuPrice'], 2); //js选择sku数组  价格
            $skuprice[$newskuValue]['quantity'] = $productSku[$i]['quantity']; //js选择sku数组  库存
            $skuprice[$newskuValue]['id'] = $productSku[$i]['id']; //js选择sku数组  id

            $allcount += $productSku[$i]['quantity'];
            $skulist = $productSku[$i]['productSkuValue'];
            for ($k = 0; $k < count($skulist); $k++) {
                $skuValuelist[$i]['skuValueId'][] = $skulist[$k]['skuValueId'];
                $skuValuelist[$i]['skuValue'][] = $skulist[$k]['skuValue'];
            }
        }
        for ($m = 0; $m < count($skuValuelist); $m++) {
            sort($skuValuelist[$m]['skuValueId']);
        }
        $skuprice = json_encode($skuprice);
        $skuprice = str_replace('[', '', $skuprice);
        $skuprice = str_replace(']', '', $skuprice);

        $product = $row['product'];
        $product['currentProductSkuId'] = $row['currentProductSkuId'];
        $keywords = explode(',', $row['product']['keywords']);

        $params = array(
            'GetProductCommentByIdReq' => array(
//                'sellerId' => '0',
                'productId' => $product['id']
            )
        );

        $commont_row = $api2->apiclient('/LdAccountServer/comment/getProductCommentById', $params);

        if (isset($_POST['ajax']) && $_POST['ajax'] === 'product-form') {
            echo CActiveForm::validate($model);
            Yii::app()->end();
        }

        if ($_POST['nowbuy']) {
            if (isset($_POST['ProductForm'])) {
                $model->attributes = $_POST['ProductForm'];

                if ($model->validate()) {
                    $apiurl_addUserCart = "/LdAccountServer/order/addUserCart";
                    $params_addUserCart = array(
                        'AddUserCartReq' => array(
                            'userId' => Yii::app()->user->id,
                            'sellerId' => $model->sellerid,
                            'productSkuId' => $model->skuid,
                            'amount' => $model->skuquantity
                        )
                    );

                    if (Yii::app()->user->id) {
                        if ($model->sellerid <= 0) {
                            Yii::app()->user->setFlash('message', '卖家不存在');
                        } elseif ($model->skuid <= 0) {
                            Yii::app()->user->setFlash('message', '请选择商品分类');
                        } elseif ($model->skuquantity <= 0) {
                            Yii::app()->user->setFlash('message', '购买数量不能为0');
                        } else {
                            $addUserCart_row = $api2->apiclient($apiurl_addUserCart, $params_addUserCart);
                            if ($addUserCart_row['code'] == 0) {
                                $this->redirect(array('order/confirmation'));
                            } else {
                                Yii::app()->user->setFlash('message', $addUserCart_row['ExceptionRsp']['msg']);
                            }
                        }
                    } else {
                        Yii::app()->user->setFlash('message', '请先登录');
                    }
                }
            }
        }

        /*
         * 还购买了
         */
        $row_samebuy = @file_get_contents('http://' . Yii::app()->params['apiHostProduct'] . ':' . Yii::app()->params['apiPortProduct'] . '/ProductCenter/select?q=**' . $zoneid . '&fq=status:1&wt=json&indent=true&sort=saleCount+desc&start=0&rows=3');
        $row_samebuy = CJSON::decode($row_samebuy);
//        Controller::RenderPartial('product', array('product' => $product, 'keywords' => $keywords, 'commont' => $commont_row['GetProductCommentByIdRsp']['productComments'], 'productSku' => $productSku, 'skuprice' => $skuprice, 'model' => $model, 'skuValuelist' => $skuValuelist, 'allcount' => $allcount, 'row_samebuy' => $row_samebuy['QueryResponse']['results']));
        $this->render('product', array('product' => $product, 'keywords' => $keywords, 'commont' => $commont_row['GetProductCommentByIdRsp']['productComments'], 'productSku' => $productSku, 'skuprice' => $skuprice, 'model' => $model, 'skuValuelist' => $skuValuelist, 'allcount' => $allcount, 'row_samebuy' => $row_samebuy['QueryResponse']['results']));
    }

    public function actionError() {
        if ($error = Yii::app()->errorHandler->error) {
            if (Yii::app()->request->isAjaxRequest) {
                echo $error['message'];
            } else {
                $this->render('error', $error);
            }
        }
    }

    public function actionLogin() {
        if (Yii::app()->user->isGuest) {
            $cs = Yii::app()->clientScript;
            $cs->registerCssFile(Yii::app()->baseUrl . '/css/login.css');
            $cs->registerScriptFile(Yii::app()->request->baseUrl . "/js/zhbform.js", CClientScript::POS_HEAD);
            $model = new LoginForm('login');

            if (isset($_POST['ajax']) && $_POST['ajax'] === 'login-form') {
                echo CActiveForm::validate($model);
                Yii::app()->end();
            }

            if (isset($_POST['LoginForm'])) {
                $model->attributes = $_POST['LoginForm'];

                if ($model->validate() && $model->login())
                    $this->redirect(Yii::app()->homeUrl);
            }
            $this->layout = 'clearmain';
            $this->render('login', array('model' => $model));
        }else {
            header("location: " . Yii::app()->params['homeUrl']);
        }
    }

    public function actionRegister() {
        if (Yii::app()->user->isGuest) {
            $cs = Yii::app()->clientScript;
            $cs->registerCssFile(Yii::app()->baseUrl . '/css/login.css');
            $cs->registerScriptFile(Yii::app()->request->baseUrl . "/js/zhbform.js", CClientScript::POS_HEAD);

            $model = new LoginForm('register');

            if (isset($_POST['ajax']) && $_POST['ajax'] === 'reg-form') {
                echo CActiveForm::validate($model);
                Yii::app()->end();
            }

            if (isset($_POST['LoginForm'])) {
                $model->attributes = $_POST['LoginForm'];

                if ($model->validate() && $model->register())
                    $this->redirect($this->createUrl('/'));
            }

            $this->layout = 'clearmain';
            $this->render('register', array('model' => $model));
        }else {
            header("location: " . Yii::app()->params['homeUrl']);
        }
    }

    public function actionLogout() {
        Yii::app()->user->logout();
        $this->redirect(Yii::app()->homeUrl);
    }
    
    public function actionMobile(){
        $this->layout = 'realclearmain';
        $this->render('mobile');
    }

}
